package router

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

// SetupRouter :
func SetupRouter() *gin.Engine {
	router := gin.Default()
	router.Use(accessControlAllow())
	// other
	RegisterRouter(router)
	return router
}

// 定义全局的CORS中间件
func accessControlAllow() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Writer.Header().Add("Access-Control-Allow-Headers", "access-control-allow-headers,"+
			"access-control-allow-methods,access-control-allow-origin,cache-control,content-type,utoken,appSecret")
		c.Writer.Header().Add("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Add("Access-Control-Allow-Methods", "POST,GET,OPTIONS,PUT,DELETE,PATCH")
		if c.Request.Method == "OPTIONS" {
			c.Status(http.StatusNoContent)
			c.Abort()
			return
		}
		c.Next()
	}
}
